################
#    SET UP    #
################


library(groundhog)
pkgs <- c("ggpubr", 
          "tidyverse", 
          "cowplot",
          "RSQLite",
          "sp",
          "conflicted", 
          "RColorBrewer",
          "janitor", 
          "flextable", 
          "officer",
          "corrplot",
          "stargazer"
)

groundhog.library(pkg = pkgs, date = "2023-07-15")
conflict_prefer("ggsave", winner = "ggplot2")
conflicts_prefer(dplyr::filter)

spreadsheets_to_keep <-
  c("descriptive_case_outcome_plot",
    "ctab_pos_by_pos",
    "levels_of_claim",
    "etype_race",
    "file_attr_petition_clean",
    "cand_info_all"
  )

load("./data_clean/main_analysis.Rdata")

kenya_law <- read_rds("./data_clean/kenya_law.rds")

cand_info_all <- read_csv("./data_clean/candidate_info.csv",
                          col_select = -1) 


####################
# DATA PREPARATION #
####################

#joining petition info + petitioner info + respondent info 
file_attr_petresp <- 
  left_join(
    mutate(descriptive_file_attr,
           fileID = as.integer(as.character(fileID))),
    select(petitioner_complete,
           fileID,
           RQDA_name,
           Gender,
           party_pet,
           ValidVotesPerc,
           status_pet,
           election_rank),
    by= "fileID") %>%
  rename(name_pet = RQDA_name,
         gender_pet = Gender,
         election_rank_pet = election_rank,
         valid_votes_pet = ValidVotesPerc) %>%
  left_join(
    select(respondent_complete,
           fileID,
           CandName,
           Gender,
           party_resp,
           ValidVotes.,
           status_resp) %>%
      mutate(fileID = as.integer(fileID)),
    by= "fileID") %>%
  rename(name_resp = CandName,
         gender_resp = Gender,
         valid_votes_resp = ValidVotes.) %>%
  mutate(vote_diff = valid_votes_resp - valid_votes_pet)



#merging case level (a case can have multiple petitions) candidature data to kenyalaw data (petition archive)
kenyalaw_cand <- 
  kenyalaw %>%
  left_join(
    select(case_files,
           unit_name,
           position,
           petitioner_candidate, 
           file_outcome,
           file_type,
           fid),
    by = c("electoral_area" = "unit_name","position")) %>%
  left_join(select(petitioner_complete,
                   fileID,
                   fullname),
            by = c("fid" = "fileID")) %>%
  rename(pet_cand_name = fullname)


#identifying potential bargaining chip petitioners
bargaining_chip <-
  kenyalaw_cand %>%
  filter(appeal_attempt == 0 & 
           (petitioner_candidate == 1 | is.na(petitioner_candidate)) & 
           file_outcome != "void_election")

write.csv(bargaining_chip, file = "./data_clean/bargaining_chip.csv", row.names = FALSE)


### Manual check: ###
#manual check and labeling of each potential bargaining chip petitioners case by case investigation


#importing back the list of potential bargaining chip petitioners after manual labeling
bargaining_findings <- read.csv("./data_clean/bargaining_chip_findings.csv", stringsAsFactors = FALSE) %>%
  filter(file_outcome != "void_election" & #removed void election observations
           electoral_area != "wajir_west" & #removed the problematic Wajir west case
           !grepl("Asman", petitioners, ignore.case = T)) %>% #and the Saboti case that had issues with Kenya Law 
  mutate(govt_position_binary = ifelse(government_position == "no", 0, 1),
         rerun_binary = ifelse(rerun_2017 == "yes", 1, 0),
         petition_dismissed = ifelse(withdrawn == 0 & struck_out == 0, 1, 0))
#Note: the Saboti case was included in the final set


#cleaning the labelled bargaining chip petitioner table
bargaining_findings_clean <- bargaining_findings %>%
  select(-c(daily_nation,
            the_standard,
            the_star,
            google,
            rerun_source)) %>%
  mutate(govt_position_binary = ifelse(date_appointment %in% c("2013",
                                                               "2014",
                                                               "2015"), 
                                       1, 
                                       0), #I include appointments made in 2015
         date_appointment = as.numeric(date_appointment),
         government_position = ifelse(date_appointment %in% c("2013",
                                                              "2014",
                                                              "2015"),
                                      government_position, 
                                      NA))



#there is no correlation between having won a government position and rerunning
bargaining_findings_sum <- bargaining_findings %>%
  select(govt_position_binary, 
         rerun_binary, 
         withdrawn, 
         struck_out, 
         petition_dismissed,
         party_position,
         party_position_elected,
         county_position) %>%
  summarise_all(sum)


write.csv(bargaining_findings, file = "./data_clean/bargaining_chip_findings.csv", row.names = F)




#fraud or not - type of case using codes
#list of code that were categorized
case_type_codes <- read.csv("./data_clean/case_type_codes.csv",
                            stringsAsFactors = FALSE)



#match the categorized codes to cfid_count to get the total codings of each category
cfid_count <- cfid_count |> ungroup()

case_type_code_count <- 
  left_join(cfid_count,
            select(case_type_codes,
                   -memo),
            by = c("codename" = "name")) %>%
  rename(cid = id,
         freq = n)



#the total number of codings by code type
case_type_code_count %>% 
  group_by(case_type) %>%
  summarize(total = sum(freq))
#there are over double the number of procedural codings than fraud codings


#looking at the distribution within petitions
petition_type_sum <- case_type_code_count %>%
  group_by(fid, case_type) %>%
  summarize(total = sum(freq)) %>%
  mutate(case_type = ifelse(case_type == "", "other", case_type)) %>%
  spread(case_type, total, fill = 0) %>% #fill in 0s so that the plot has no gaps
  gather(case_type, total, -fid)


#changed to spread format to compare the distribution of codings 
petition_type_sum_spread <- petition_type_sum %>%
  spread(case_type, total) %>%
  mutate(sum_codings = fraud + procedural + other,
         prop_fraud = fraud/sum_codings *100,
         type_fraud = ifelse(prop_fraud > 50, 1, 0))


#checking the distribution
ggplot(petition_type_sum_spread, aes(prop_fraud)) +
  geom_density()

ggplot(petition_type_sum, aes(x=fid, y=total, fill=case_type)) +
  geom_area(position = "stack") +
  theme_bw()
#only very few cases where the procedural codings are fewer than fraud codings (13/83)



#export so that the petitions can be manually coded by content 
write.csv(select(petition_type_attributes,
                 caseid,
                 fid,
                 file_type,
                 prop_fraud,
                 position,
                 unit_name,
                 vote_diff),
          "./data_clean/case_manual_coding.csv",
          row.names = F)



### Manual check: ###
  #manual check and labeling of each petition was done by reading the entire text of the petition (and appeals)


#import the manually labeled cases by scope and legitimacy (56 cases out of 71 cases were NOT withdrawn/struck out)
case_legit_scope <- read.csv("./data_clean/manual_case_coding_legit_scope.csv", 
                             stringsAsFactors = FALSE)


#determing in the petition strategy label (these are the initial set of categories we came up with. Category names are updated in paper.)
case_strategy <- left_join(mutate(petition_type_attributes,
                                  vote_diff = case_when(fid == 13 ~ 11, 
                                                        fid == 30 ~ 8,
                                                        fid == 33 ~ 0.1, #quick fix for now for the appeal cases
                                                        fid == 15 ~ 5.39,
                                                        fid == 67 ~ 13.76,
                                                        fid == 95 ~ 13.9,
                                                        fid == 106 ~ 32.18, #quick fix for non-runnerup petitioners
                                                        TRUE ~ vote_diff)),
                           select(case_legit_scope,
                                  fid, 
                                  legitimacy, 
                                  scope), 
                           by = "fid") %>% 
  mutate(strategy = case_when(vote_diff < 10 & legitimacy == 1 & scope == 1 ~ "sincere",
                              vote_diff < 10 & !(legitimacy == 1 & scope == 1) ~ "bargaining_chip",
                              vote_diff > 10 & legitimacy == 1 & scope == 1 ~ "symbolic",
                              vote_diff > 10 & !(legitimacy == 1 & scope == 1) ~ "sore_loser")) 
#when the vote difference is high, it's less likely that the case will have scope
  #all files are individual petitions


case_strategy_simple <- select(case_strategy,
                               fid, 
                               caseid,
                               prop_fraud,
                               type_fraud,
                               position,
                               unit_name,
                               vote_diff,
                               legitimacy,
                               scope,
                               strategy)

write.csv(case_strategy_simple, 
          "./data_clean/petition_strategies.csv",
          row.names = F)



#full dataframe of all 71 petitions
petition_strategy_full <- 
  full_join(
    case_strategy_simple,
    bargaining_findings_clean %>%
      select(
        appeal_attempt,
        fid,
        government_position,
        govt_position_binary,
        date_appointment,
        rerun_binary,
        rerun_2017,
        position_2017,
        unit_2017,
        result_2017,
        file_outcome
      ),
    by = "fid"
  ) %>% 
  rename(file_outcome_b = file_outcome) %>%
  left_join(select(case_files,
                   file_outcome,
                   caseid),
            by = "caseid") %>%
  mutate(
    appeal_attempt = ifelse(is.na(appeal_attempt) &
                              file_outcome == "valid_election", 1, 0),
    govt_position_binary = ifelse(is.na(govt_position_binary), 0, govt_position_binary),
    file_outcome = ifelse(is.na(file_outcome), file_outcome_b, file_outcome),
    strategy = ifelse(
      file_outcome %in% c("void_election", "valid_election"),
      strategy,
      "unsure"
    )
  ) #this is for the struck out or withdrawn petitions



#export the table of all petitions to manually check and label if the petitioner reran in a future election
rerun_check <- left_join(petition_strategy_full,
                         select(file_attr_petresp,
                                fileID, 
                                name_pet),
                         by = c("fid" = "fileID")) %>%
  select(fid,
         caseid,
         name_pet,
         position,
         unit_name,
         rerun_binary,
         rerun_2017,
         position_2017,
         unit_2017,
         result_2017,
         file_outcome)


write.csv(rerun_check, 
          "./data_clean/rerun_check.csv",
          row.names = F)


### Manual check: ###
  #manual check of petitioner re-run status:
    #used kenya.ynr.mysociety.org to check for reruns
    #manually added names for the problematic 3 petitions (where appeals were coded)
    #note: Seif Kajembe died in 2017
    #note: Thuo Mathenge tried to run again as Nyeri governor, but he was banned by the court




#Import after checking and manually labeling reruns 
rerun_checked <- read.csv("./data_clean/rerun_checked.csv",
                          stringsAsFactors = FALSE)


#need to add party attributes, but first need to fix the appeal cases (match it to the original file id)
temp_file_attr_petresp <- file_attr_petresp %>%
  filter(!(fileID %in% c(13, 30, 33))) %>%
  mutate(fileID = case_when(fileID == 138 ~ as.integer(13),
                            fileID == 139 ~ as.integer(30),
                            fileID == 128 ~ as.integer(33),
                            TRUE ~ fileID))



#merging dataframes with petitions, case outcome, and rerun statuses
petition_rerun <- full_join(select(petition_strategy_full,
                                            -c(caseid,
                                               position,
                                               unit_name,
                                               rerun_binary,
                                               rerun_2017,
                                               position_2017,
                                               unit_2017,
                                               result_2017,
                                               file_outcome)),
                                     rerun_checked,
                                     by = "fid") %>%
  left_join(select(temp_file_attr_petresp,
                   fileID,
                   party_pet, 
                   vote_diff,
                   unit_name,
                   position) %>%
              rename(vote_diff_b = vote_diff,
                     unit_name_b = unit_name,
                     position_b = position),
            by = c("fid" = "fileID")) %>%
  left_join(select(case_files,
                   fid,
                   caseid) %>%
              rename(caseid_b = caseid),
            by = "fid") %>%
  left_join(select(petitioner_complete,
                   fileID,
                   status_pet),
            by = c("fid" = "fileID")) %>%
  rename(strategy_petition_text = strategy) %>%
  mutate(rerun_binary = ifelse(rerun_2017 == "yes", 1, 0),
         vote_diff = ifelse(file_outcome %in% c("valid_election", "void_election"), 
                            vote_diff, 
                            vote_diff_b),
         position = ifelse(file_outcome %in% c("valid_election", "void_election"), 
                           position, 
                           position_b),
         unit_name = ifelse(file_outcome %in% c("valid_election", "void_election"), 
                            unit_name, 
                            unit_name_b),
         caseid = ifelse(file_outcome %in% c("valid_election", "void_election"), 
                         caseid, 
                         caseid_b),
         coalition = case_when(party_pet %in% c("TNA", 
                                                "URP",
                                                "NARC",
                                                "RC", 
                                                "UDF",
                                                "NFK",
                                                "KANU",
                                                "APK",
                                                "KADU-A",
                                                "PDP",
                                                "CCUZ", 
                                                "FORD-P") ~ "Jubilee",
                               party_pet %in% c("ODM", 
                                                "WDM-K", 
                                                "FORD-K",
                                                "FPK", 
                                                "MP", 
                                                "TIP") ~ "CORD",
                               TRUE ~ "Other")) %>%
  left_join(select(case_attributes,
                   caseID,
                   case_outcome),
            by = c("caseid" = "caseID")) %>%
  select(-c(file_outcome_b,
            vote_diff_b,
            position_b,
            unit_name_b,
            caseid_b))
#this includes the struck out & withdrawn cases


#party categorization into coalitions:

#first, the list of parties in jubilee and CORD
  #got list from https://www.eisa.org.za/wep/ken2013coalitions.htm
#expanding the CORD list
  #using appendix: https://www.cartercenter.org/resources/pdfs/news/peace_publications/election_reports/kenya-final-101613.pdf

#Jubilee = APK, TNA, URP, NARC, RC (republican congress), KADU-Asili, PDP, 
#CCU, KANU, UDF, New FORD-K (NFK), FORD-P 
#CORD = ODM, Wiper, FORD-K, MP, TIP, FPK
#Amani (not included under Jubilee) = UDF, New FORD-K (NFK), KANU
#Amani was later included under Jubilee, so it was added to jubilee's list


# The number of petitioners and non-candidates

  #Anomalies:
    #The case of Lamu governor was an anomaly where the petition was not available in the petition archive
      #the original petitioner was a candidate but it is not recorded as such
    #Lamu women rep was filed separately, once for by a voter and once by a candidate - the candidate one was struck out but the voter one moved to the Supreme Court - only the voter one is included 

table(case_files$petitioner_candidate)

# Cases with multiple candidate petitioners - export to manually label the primary petitioner
multiple_petitioner_cases <-
  select(petition_rerun,
         fid,
         name_pet,
         position,
         unit_name) |>
  arrange(unit_name, position)

write.csv(multiple_petitioner_cases, 
          "./data_clean/multiple_petitioner_cases.csv",
          row.names = F)

### Manual check: ###
  #Manully checked for the primary petitioner in the petition text
  #Note for Mavoko petition: multiple candidates petitioned but I put the fifth place as the main petitioner because the main allegation was that his name and photo were missing
  #Note for Kilifi gov petition: the petitioner with the highest votes was not chosen - the first petitioner was chosen instead (9th place)

mult_petitioner_checked <- read.csv("./data_clean/multiple_petitioner_checked.csv", 
                                    stringsAsFactors = FALSE) %>%
  mutate(mult_cand = ifelse(KED_name == "", 0, 1)) %>%
  arrange(fid, unit_name, position)

#get the duplicated cases with the main petitioner and the number of duplicates
dup_pet <- mult_petitioner_checked |> 
  group_by(across(c("fid", "position"))) %>% 
  mutate(n_pet = n()) |>
  filter(n_pet > 1) %>%
  slice(1) |>
  ungroup()


#complete table with petitions, case outcome, rerun, and multiple petitioner statuses
petition_full <- 
  left_join(petition_rerun, select(dup_pet, fid, n_pet))



#Group by coalitions
party_code <- select(cand_info_all, 
                     PartyCode,
                     PartyName) %>%
  group_by(PartyCode) %>%
  summarise_all(first) %>%
  mutate(coalition = case_when(PartyCode %in% c("TNA", #let's add a coalition column
                                                "URP",
                                                "NARC",
                                                "RC", 
                                                "UDF",
                                                "NFK",
                                                "KANU",
                                                "APK",
                                                "KADU-A",
                                                "PDP",
                                                "CCUZ", 
                                                "FORD-P") ~ "Jubilee",
                               PartyCode %in% c("ODM", 
                                                "WDM-K", 
                                                "FORD-K",
                                                "FPK", 
                                                "MP", 
                                                "TIP") ~ "CORD",
                               TRUE ~ "Other"))



#match petition information to the table of all losing candidates
#candrank (CandRank) is the unique identifier for both RQDA_KED_matched and cand_info_all

cand_info_losers <- select(cand_info_all,
                           -X1) %>%
  filter(Position != 1) %>%
  left_join(select(ungroup(RQDA_KED_matched),
                   candrank,
                   fullname,
                   fileID),
            by = c("CandRank" = "candrank")) %>%
  left_join(select(mult_petitioner_checked,
                   KED_name,
                   mult_cand),
            by = c("CandName" = "KED_name")) %>%
  left_join(select(party_code,
                   PartyCode,
                   coalition),
            by = "PartyCode") %>%
  mutate(petition = ifelse(is.na(fileID) & is.na(mult_cand), 0, 1))  %>%
  filter(!(fileID %in% c(11, 80))) #removing the Lamu women rep and Baringo South cases that are anomalies



cand_losers_simple <- select(cand_info_losers,
                             coalition,
                             petition) %>%
  mutate(petition = ifelse(petition == 1, "petition", "no_petition")) %>%
  add_count(coalition) %>%
  add_count(coalition, petition) %>%
  distinct() %>%
  rename(total = n,
         number = nn) %>%
  mutate(perc = round(number/total *100, 2))


#function capitalize every first letter of word (to improve legibility)
simpleCap <- function(x) {
  s <- strsplit(x, " ")[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2),
        sep="", collapse=" ")
}


#which petitioners are missing?
compare_missing <- full_join(select(ungroup(RQDA_KED_matched),
                                    matched_name,
                                    position,
                                    unit_name,
                                    fileID),
                             left_join(petition_full,
                                       select(petitioner_complete,
                                              RQDA_name,
                                              matched_name),
                                       by = c("name_pet" = "RQDA_name")),
                             by = c("matched_name"))
#1. Lamu women rep 
#a strange case that had multiple files associated to it (multiple non-consolidated petitions)
#one by a petitioner (struck out) and one by a voter (made it to supreme court)

#2. Baringo South mp
#this is another strange case where the petition is about appealing the decision to have a petition that was struck out


################
# THE FIGURES  #
################

#Fig 1: Number of Petitioners Filed by Coalition
ggplot(cand_losers_simple, aes(x = coalition,
                               y = number,
                               fill = petition)) +
  geom_bar(stat = "identity",
           position = "dodge") +
  geom_text(aes(y= number,
                label= paste0("(", round(perc, 0), "%)")),
            position = position_dodge(width = 0.9),
            vjust = -1,
            hjust = 0.2,
            size = 3) +
  geom_text(aes(y= number,
                label= number),
            position = position_dodge(width = 0.9),
            vjust = -1,
            hjust = 1.8,
            size = 3) +
  labs(x = "Coalition",
       y = "# of Candidates",
       title = "Number of petitions filed by coalition") +
  scale_fill_manual(name="",
                    labels=c("Did not file petition", "Petition filed"),
                    breaks = c("no_petition", "petition"),
                    values = c("grey80", "grey20")) +
  scale_y_continuous(limits = c(0, 1050)) + 
  theme_minimal()

#ggsave("./figs/figure1_bw_case_by_party.pdf", height = 4, width = 8) 




################
#  THE TABLES  #
################


#chi sq test to compare proportions
prop_petitions_coalition <- select(cand_losers_simple,
                                   coalition,
                                   petition,
                                   number) %>%
  spread(coalition, number)

sink(file = "./tables/chisq_ftn.txt", 
     append = FALSE)
print(stats::chisq.test(as.matrix(prop_petitions_coalition[,-1])))
sink()


petition_strategy_rerun <-
  petition_full %>% mutate(
    case_probability = case_when(
      vote_diff <= 10 & scope == 1 & legitimacy == 1 ~ "High",
      vote_diff <= 10  & ((scope + legitimacy) < 2) ~ "Medium",
      vote_diff >= 10 | is.na(scope) & is.na(legitimacy)  ~ "Low"
    ),
    neither = ifelse(rerun_binary != 1 &
                       govt_position_binary != 1, 1, 0)
  ) %>%
  mutate(case_probability = fct_relevel(as_factor(case_probability), c("Low", "Medium", "High")))

rerun <- select(petition_strategy_rerun,
                fid,
                case_probability, 
                rerun_binary) %>%
  group_by(case_probability, rerun_binary) %>%
  summarise(count = n()) %>%
  spread(rerun_binary, count) %>%
  rename(Reputation = `1`) %>%
  select(case_probability, Reputation)

rerun_65 <- 
  petition_strategy_rerun |>
  filter(is.na(n_pet)) |>
  select(fid, case_probability, rerun_binary) %>%
  group_by(case_probability, rerun_binary) %>%
  summarise(count = n()) %>%
  spread(rerun_binary, count) %>%
  rename(Reputation = `1`) %>%
  select(case_probability, Reputation)


position_65 <- 
  petition_strategy_rerun |>
  filter(is.na(n_pet)) |>
  select(fid, case_probability, govt_position_binary) %>%
  group_by(case_probability, govt_position_binary) %>%
  summarise(count = n()) %>%
  spread(govt_position_binary, count) %>%
  rename(Bargaining = `1`) %>%
  dplyr::select(case_probability, Bargaining)

position <- dplyr::select(petition_strategy_rerun,
                          fid,
                          case_probability,
                          govt_position_binary) %>%
  group_by(case_probability, govt_position_binary) %>%
  summarise(count = n()) %>%
  spread(govt_position_binary, count) %>%
  rename(Bargaining = `1`) %>%
  dplyr::select(case_probability, Bargaining)

neither <- dplyr::select(petition_strategy_rerun,
                         fid,
                         case_probability, 
                         neither) %>%
  group_by(case_probability, neither) %>%
  summarise(count = n()) %>%
  spread(neither, count) %>%
  rename(Neither = `1`) %>%
  dplyr::select(case_probability, Neither)

neither_65 <- 
  petition_strategy_rerun |>
  filter(is.na(n_pet)) |>
  select(fid,case_probability, neither) %>%
  group_by(case_probability, neither) %>%
  summarise(count = n()) %>%
  spread(neither, count) %>%
  rename(Neither = `1`) %>%
  dplyr::select(case_probability, Neither)


# PAPER TABLE 3
make_imp_table <- function(rerun, position, neither, isfull = TRUE) {
  implications <- full_join(rerun, position) %>%
    full_join(neither) 
  
  if(isfull) implications$`Cases` <-   as.vector(table(petition_strategy_rerun$case_probability))
  if(!isfull) {
    temp <- filter(petition_strategy_rerun, is.na(n_pet))
    implications$`Cases` <-    as.vector(table(temp$case_probability))
  } 
  
  implications <- implications %>% 
    mutate(`Reputation Pct` = scales::percent(Reputation/Cases),
           `Bargaining Pct` = scales::percent(Bargaining/Cases),
           `Neither Pct` = scales::percent(Neither/Cases)
    ) %>%
    dplyr::select(case_probability, Reputation, `Reputation Pct`,  Bargaining, `Bargaining Pct`, Neither, `Neither Pct`, Cases) %>%
    rename(`Case Probability` = case_probability) %>%
    adorn_totals("row") 
}

implications <- make_imp_table(rerun, position, neither)
implications_65 <- make_imp_table(rerun_65, position_65, neither_65, isfull = FALSE)


imp_out <- flextable::flextable(implications)
imp_out_65 <- flextable::flextable(implications_65)

#this outputs the doc directly into word
doc <- read_docx()
doc <- body_add_flextable(doc, value = imp_out)
fileout <- tempfile(fileext = ".docx")
# fileout <- "test.docx" # uncomment to write in your working directory
print(doc, target = "tables/table3_implications.docx")



# APPENDIX TABLE B1

#Table of all petitioners and how they were categorized
strategy_all_table <- select(petition_strategy_rerun,
                                 name_pet,
                                 coalition,
                                 position,
                                 unit_name,
                                 vote_diff,
                                 legitimacy,
                                 scope,
                                 case_probability,
                                 govt_position_binary,
                                 rerun_binary,
) %>%
  mutate(position = sapply(str_replace_all(position, "_", " "), simpleCap),
         unit_name = sapply(str_replace_all(unit_name, "_", " "), simpleCap),
         vote_diff = paste0(round(vote_diff,2),"%"),
         legitimacy = case_when(legitimacy == 1 ~ "Yes",
                                legitimacy == 0 ~ "No",
                                TRUE ~ "NA"),
         scope = case_when(scope == 1 ~ "Yes",
                           scope == 0 ~ "No",
                           TRUE ~ "NA"),
         govt_position_binary = ifelse(govt_position_binary == 1, "Yes", "No"),
         rerun_binary = ifelse(rerun_binary == 1, "Yes", "No")) %>%
  arrange(unit_name, position) %>%
  rowid_to_column(var = "No.") %>%
  select(`No.`, everything())

doc <- read_docx()
imp_out2 <- flextable(strategy_all_table)
imp_out2 <- fontsize(imp_out2, size = 9, part = "body")
imp_out2 <- theme_vanilla(imp_out2) 
doc <- body_add_flextable(doc, value = imp_out2) 
doc <- body_end_section_landscape(doc) 
fileout <- tempfile(fileext = ".docx")
# fileout <- "test.docx" # uncomment to write in your working directory
print(doc, target = "tables/table_B1_everybody.docx")

print(imp_out, target = "./tables/table_B1_everybody.docx")



# APPENDIX TABLE B2

doc_65 <- read_docx()
doc_65 <- body_add_flextable(doc_65, value = imp_out_65)
fileout_65 <- tempfile(fileext = ".docx")
# fileout <- "test.docx" # uncomment to write in your working directory
print(doc_65, target = "tables/table_B2_implications_65.docx")





